<template>
  <el-dialog
    :title="formData.id?'编辑分类':'添加分类'"
    :visible="showDialog"
    @close="close"
  >
    <el-form ref="form" label-width="70px" :rules="rules" :model="formData">
      <el-form-item label="标题" prop="title">
        <el-input v-model="formData.title" />
      </el-form-item>
      <el-form-item label="描述" prop="desc">
        <el-input v-model="formData.desc" />
      </el-form-item>
      <el-form-item label="封面">
        <UploadImage ref="img1" />
        <el-input v-model="formData.image" placeholder="强制设置图片跳过上传" />
      </el-form-item>
    </el-form>
    <el-row type="flex" justify="end">
      <el-button type="primary" size="small" @click="submit">确定</el-button>
      <el-button size="small" @click="close">取消</el-button>
    </el-row>
  </el-dialog>
</template>

<script>
import { addfenlei, onefenlei, editfenlei } from '@/api/fenlei'
import UploadImage from '../UploadImage/index.vue'
export default {
  components: {
    UploadImage
  },
  props: {
    showDialog: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      formData: {
        title: '',
        desc: '',
        image: ''
      },
      rules: {
        title: [
          { required: true, message: '标题不能为空', trigger: 'blur' }
        ],
        desc: [
          { required: true, message: '描述不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    close() {
      this.$emit('close', false)
      this.$refs.form.resetFields()
      this.formData = {}
      this.$refs.img1.imgUrl = ''
    },
    // 编辑新增
    async submit() {
      this.formData.image = this.$refs.img1.imgUrl
      // 如果有id
      if (this.formData.id) {
        // 编辑修改
        await editfenlei(this.formData)
      } else {
        // 新增
        await addfenlei(this.formData)
      }
      this.close()
      this.$emit('update')
    },
    // 获取单个分类
    async getonefenlei(id) {
      const res = await onefenlei(id)
      this.formData = res.data
      this.$refs.img1.imgUrl = res.data.image
    }
  }
}
</script>

<style>

</style>
